package com.online_exam.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.online_exam.domain.User;
import com.online_exam.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JwtUtil {
    private static final String SING = "xiewang&ek";

    public static String getToken(Map<String,String>map){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 3);
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v );
        });
        String token = builder.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    public static User DecodeByToken(HttpServletRequest request, UserService userService){
        String token = request.getHeader("token");
        DecodedJWT decode = JWT.decode(token);
        String userName = decode.getClaim("userName").asString();
        if (userName!= null){
            User user = userService.selectByUsername(userName);
            System.out.println("获取到用户为："+user.getUserName());
        }
        return null;
    }
}
